import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
import os
import sys
from common.device import DeviceInfo
from routers import cursor


def get_assets_path():
    # 判断是否是打包后的可执行文件
    if getattr(sys, 'frozen', False):
        # 如果是打包后的程序，使用 _MEIPASS
        base_path = sys._MEIPASS
    else:
        # 如果是开发环境，使用当前目录
        base_path = os.path.dirname(os.path.abspath(__file__))

    return os.path.join(base_path, 'assets')


app = FastAPI()

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 获取assets目录路径
assets_path = get_assets_path()

# 确保assets目录存在
if not os.path.exists(assets_path):
    os.makedirs(assets_path)

# 挂载静态文件
app.mount("/assets", StaticFiles(directory=assets_path), name="assets")

# 注册路由
app.include_router(cursor.router)


@app.get("/", response_class=HTMLResponse)
async def read_index():
    try:
        file_path = os.path.join(get_assets_path(), "login.html")
        with open(file_path, "r", encoding="utf-8") as file:
            return file.read()
    except Exception as e:
        return HTMLResponse(content=f"加载登录页面失败: {str(e)}", status_code=500)


@app.get("/main", response_class=HTMLResponse)
async def read_main_page():
    try:
        file_path = os.path.join(get_assets_path(), "sidebar.html")
        with open(file_path, "r", encoding="utf-8") as file:
            return file.read()
    except Exception as e:
        return HTMLResponse(content=f"加载主页面失败: {str(e)}", status_code=500)


@app.get("/pages/{page_name}", response_class=HTMLResponse)
async def read_page(page_name: str):
    """动态页面路由"""
    try:
        # 移除.html后缀（如果存在）
        page_name = page_name.replace('.html', '')
        file_path = os.path.join(get_assets_path(), "pages", f"{page_name}.html")

        # 检查文件是否存在
        if not os.path.exists(file_path):
            return HTMLResponse(content=f"页面 {page_name} 不存在", status_code=404)

        with open(file_path, "r", encoding="utf-8") as file:
            return file.read()
    except Exception as e:
        return HTMLResponse(content=f"加载页面失败: {str(e)}", status_code=500)


@app.get("/register")
async def register_page():
    """注册页面"""
    try:
        file_path = os.path.join(get_assets_path(), "register.html")
        return FileResponse(file_path)
    except Exception as e:
        return HTMLResponse(content=f"加载注册页面失败: {str(e)}", status_code=500)


@app.get("/api/device/info")
async def get_device_info():
    """获取设备信息"""
    try:
        device = DeviceInfo()
        return {"code": 200, "msg": "success", "data": device.get_info()}
    except Exception as e:
        return {"code": 500, "msg": str(e)}


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=9999, reload=True)
